<?php

namespace admin\controllers;

use yii\helpers\ArrayHelper;
use common\helpers\Pager;
use common\helpers\Checker;
use common\models\Category;
use common\models\Recruit;
use common\models\RecruitApplicant;

class RecruitController extends Controller {

    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'employment';

    /**
     * @name showing Recruit list
     * @return string
     */
    public function actionRecruitList()
    {
        if( ! $this->isJson) {
            return $this->render('recruit-list', [
                'modelSelector' => Category::selector($this->params['designModelCategories']),
            ]);
        }
        $params = $this->request->post();
        foreach(['start', 'end'] as $key) {
            if(empty($params[$key])) {
                continue;
            }
            $params[$key] = strtotime($params[$key]);
        }
        $params['deleted_at'] = 0;
        $query = Recruit::filterConditions(Recruit::initCondition(['employer_id', 'type', ['created_at', '>=', 'start'], ['created_at', '<', 'end'], 'status', 'deleted_at'], $params));
        // 多选选项筛选
        foreach(['category_id' => 'categories', 'model' => 'models', 'platform' => 'platforms'] as $from => $to) {
            if(in_array($from, ['category_id'])) {
                $params[$from] = max($params[$from]);
            }
            if(empty($params[$from])) {
                continue;
            }
            $query->andWhere(['like', "concat({$to}, ',')", $params[$from].',']);
        }
        // return $this->json($query->createCommand()->getRawSql());
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('employer')->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show recruit information
     * @param id int by get request
     * @return string
     */
    public function actionRecruitDetail()
    {
        if( ! $recruit = Recruit::canEdit($this->request->get('id'))) {
            return $this->error('无效的招聘（Invalid Recruit）', 'recruit/recruit-list');
        }
        return $this->render('recruit-detail', [
            'data' => $recruit,
            'modelSelector' => Category::selector($this->params['designModelCategories']),
        ]);
    }
    /**
     * @name update recruit information
     * @describe use get(id) to find Recruit
     * @return string html
     */
    public function actionRecruitUpdate()
    {
        /* @var $recruit Recruit */
        // id 为必填项，判断管理员存在状态
        $recruit = Recruit::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $recruit) {
            return $this->error('无效的招聘（Invalid Recruit）', 'recruit/recruit-list');
        }
        $param = $this->request->post();
        $param['category_id'] = max($param['category_id']);
        $recruit->loads($param);
        // $this->v($param);
        // return $this->v($recruit);
        if ( ! $recruit->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($recruit->errors(), 'recruit/recruit-detail?id='.$recruit->id);
        }
        if ($recruit->save()) {
            // 保存成功
            return $this->success('招聘（'.$recruit->title.'）更新成功（Update Success）', [
                ['title' => '前往招聘列表页', 'url' => 'recruit/recruit-list'],
                ['title' => '继续修改招聘', 'url' => 'recruit/recruit-detail?id='.$recruit->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('招聘（'.$recruit->title.'）更新失败，请重试（System Error）', 'recruit/recruit-detail?id='.$recruit->id);
    }
    /**
     * @name delete Recruit
     * @param ids array post request
     * @return string json
     */
    public function actionRecruitDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(Recruit::trashAll(['id' => $ids])) {
            return $this->json(SuccessCode, '招聘删除成功（Delete Success）');
        }
        return $this->json('System.Error', '招聘删除失败（System Error）');
    }

    /**
     * @name showing Recruit Applicant list
     * @return string
     */
    public function actionApplicantList()
    {
        if( ! $this->isJson) {
            return $this->render('applicant-list', ['recruit_id' => $this->request->find('recruit_id')]);
        }
        $rule = [
            'param' => [
                'recruit_id' => ['招聘编号', ['int', 'gt' => 0, 'required']],
                'designer_id' => ['设计师', ['int']],
                'status' => ['状态', ['inkey' => RecruitApplicant::$statusSelector]],
            ],
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message'].'（Invalid Param）');
        }
        $query = RecruitApplicant::filterConditions(RecruitApplicant::initCondition(['recruit_id', 'designer_id', 'status'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('designer')->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }
}